package hot.linklist;

import java.util.HashMap;
import java.util.Map;

public class A146 {
}
class LRUCache {
    //头部哨兵节点
    Node dummy;
    //哈希表
    Map<Integer,Node> map=new HashMap<>();
    int capacity;
    public LRUCache(int capacity) {
        this.capacity=capacity;
        dummy=new Node(1,1);
    }

    public int get(int key) {
Node node=getNode(key);
return node!=null?node.value:-1;
    }

    private Node getNode(int key) {
        if(!map.containsKey(key))return null;
        Node node = map.get(key);
        //从链表取出
        remove(node);
        //放到头部
        addHead(node);
        return node;
    }

    private void addHead(Node node) {
        node.next=dummy.next;
        dummy.next.prev=node;
        node.prev=dummy;
        dummy.next=node;
    }

    //从链表取出
    public void remove(Node node){
node.prev.next=node.next;
node.next.prev=node.prev;
    }
    public void put(int key, int value) {
       if(map.containsKey(key)){
           Node node = map.get(key);
           node.value=value;
           remove(node);
           addHead(node);
       }else{
           //是新增操作
           Node node = new Node(key, value);
           map.put(key,node);
           addHead(node);
           if(map.size()>capacity){
               Node prev = dummy.prev;
               map.remove(prev.key);
               remove(prev);
           }
       }
    }

}
class Node{
    int key;
    int value;
Node prev;
Node next;
    public Node(int key, int value) {
        this.key = key;
        this.value = value;
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache obj = new LRUCache(capacity);
 * int param_1 = obj.get(key);
 * obj.put(key,value);
 */